package com.luo.backend.repository;

import com.luo.backend.entity.Merchant;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;

/**
 * 商家数据访问接口
 */
@Repository
public interface MerchantRepository extends JpaRepository<Merchant, Long>, JpaSpecificationExecutor<Merchant> {
    
    /**
     * 根据状态查找商家（分页）
     */
    Page<Merchant> findByStatus(Integer status, Pageable pageable);
    
    /**
     * 根据名称搜索商家（分页）
     */
    @Query("SELECT m FROM Merchant m WHERE m.status = 1 AND m.name LIKE %:keyword%")
    Page<Merchant> findByNameContaining(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 根据评分排序查找商家
     */
    @Query("SELECT m FROM Merchant m WHERE m.status = 1 ORDER BY m.rating DESC, m.ratingCount DESC")
    Page<Merchant> findByStatusOrderByRating(Pageable pageable);
    
    /**
     * 根据状态查找商家并按评分和评价数量排序（分页）
     */
    @Query("SELECT m FROM Merchant m WHERE m.status = :status " +
           "ORDER BY m.rating DESC, m.ratingCount DESC")
    Page<Merchant> findByStatusOrderByRatingDescSoldCountDesc(@Param("status") Integer status, Pageable pageable);
    
    // ===== 管理员接口查询方法 =====
    
    /**
     * 统计指定状态的商家数量
     */
    long countByStatus(Integer status);
    
    // ===== 搜索功能查询方法 =====
    
    /**
     * 搜索商家（按商家名）- 分页
     */
    @Query("SELECT m FROM Merchant m WHERE m.name LIKE %:keyword% " +
           "ORDER BY m.rating DESC, m.ratingCount DESC")
    Page<Merchant> searchMerchants(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 统计搜索商家数量（按商家名）
     */
    @Query("SELECT COUNT(m) FROM Merchant m WHERE m.name LIKE %:keyword%")
    Long countMerchantsByKeyword(@Param("keyword") String keyword);
    
    /**
     * 根据所有者用户ID查找商家
     */
    Merchant findByOwnerUserId(Long ownerUserId);
    
    /**
     * 更新商家评分统计
     */
    @Modifying
    @Query("UPDATE Merchant m SET m.rating = :rating, m.ratingCount = :ratingCount WHERE m.id = :merchantId")
    void updateRatingStatistics(@Param("merchantId") Long merchantId, 
                                @Param("rating") BigDecimal rating, 
                                @Param("ratingCount") Integer ratingCount);
}
